import * as ClientUtil from './ClientUtil';
import * as AjaxUtil from './AjaxUtil';

// 获得ssoToken，如果没有， 则返回null
export function findSsoToken(): string {
  return ClientUtil.getCookie('SSO-TOKEN');
}

/**
 * 保存用户的token信息
 * 目前保存到cookie中
 * @param ssoToken
 */
export function saveSsoToken(ssoToken: string): void {
  // 登录成功, 获得domain
  let arr = location.host.split('.');
  arr.splice(0, 1);
  ClientUtil.setCookie('SSO-TOKEN', ssoToken, '.' + arr.join('.'));
}

export function gotoWxAuth(appId: string, redirectTo: string): void {
  location.replace([
    'http://cas.winnovator.cn/auth/preAuth?',
    `appId=${appId}`,
    `&redirect=${redirectTo}`
  ].join(''));
}

export function doPassport(topic: string = 'winnovator', style: string = 'gray', appId: string = "1"): void{
  const redirectTo: string = encodeURIComponent(location.href.split('#')[0]);

  location.replace([
    'http://passport.winnovator.cn?',
    `&appId=${appId}`,
    `&topic=${topic}`,
    `&style=${style}`,
    `&redirectTo=${redirectTo}`
  ].join(''));
}

/**
 * 自动处理没有权限的跳转
 * 检测ssoToken， 并验证是否有效
 * @param topic
 * @param style
 * @param appId
 */
export function startAutoAuth(topic: string = 'winnovator', style: string = 'gray', appId: string = "1"): void{

  const ssoToken: string = findSsoToken();

  if(!ssoToken){
    doPassport(topic, style, appId);
    return;
  }

  AjaxUtil.doAjax({
    url: 'http://cas.winnovator.cn/ticket/verify',
    data: {
      ticket: ssoToken
    },
    handleSuccess: (data: any) => {
      console.log('检测了token, 在有效期内');
    },
    handleError: (code: string, message: string) => {
      doPassport(topic, style, appId);
    }
  });
}
